﻿using System;
using System.ComponentModel;
using System.Net.Cache;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;
using Ionic.Zip;
using System.Security.AccessControl;

namespace AutoUpdaterDotNET
{
    internal partial class DownloadUpdateDialog : Form
    {
        private readonly string _downloadURL;
        private string _tempPath;
        public static string _ThuMucGoc
        {
            get
            {
                return System.Windows.Forms.Application.StartupPath;
            }
        }

        public DownloadUpdateDialog(string downloadURL)
        {
            InitializeComponent();

            _downloadURL = downloadURL;
        }

        private void DownloadUpdateDialogLoad(object sender, EventArgs e)
        {
            try
            {
                var webClient = new WebClient();
                var uri = new Uri(_downloadURL);
                _tempPath = string.Format(@"{0}\{1}", Path.GetTempPath(), GetFileName(_downloadURL));
                if (File.Exists(_tempPath))
                    File.Delete(_tempPath);

                webClient.DownloadProgressChanged += OnDownloadProgressChanged;
                webClient.DownloadFileCompleted += OnDownloadComplete;
                webClient.DownloadFileAsync(uri, _tempPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }

        private void OnDownloadComplete(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                //Set permission fullcontrol for everyone cho thư mục chuẩn bị extract - chính là thư mục chạy phần mềm
                DirectoryInfo myDirectoryInfo = new DirectoryInfo(_ThuMucGoc);
                DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
                foreach (FileSystemRights permission in Enum.GetValues(typeof(FileSystemRights)))
                {
                    myDirectorySecurity.AddAccessRule(
                        new FileSystemAccessRule("Everyone",
                                                 permission,
                                                 InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit | InheritanceFlags.None,
                                                 PropagationFlags.None,
                                                 AccessControlType.Allow));
                }

                //Giải nén file tại chỗ sau đó copy vào thư mục gốc
                string pathExtract = Path.GetTempPath() + @"\PAVO-Clinic";
                using (ZipFile zip = ZipFile.Read(_tempPath))
                {
                    zip.ExtractAll(pathExtract, ExtractExistingFileAction.OverwriteSilently);
                }
                string[] fileEntries = Directory.GetFiles(pathExtract);
                foreach (string fileName in fileEntries)
                {
                    if (!fileName.Contains("Ionic.Zip.dll") && !fileName.Contains("AutoUpdateClinic.NET.exe") &&
                        !fileName.Contains("PAVO-Clinic.vshost.exe"))
                    {
                        FileInfo fileNeedCopy = new FileInfo(fileName);
                        try
                        {
                            fileNeedCopy.CopyTo(_ThuMucGoc + "\\" + fileNeedCopy.Name, true);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                var processStartInfo = new ProcessStartInfo { FileName = _ThuMucGoc + @"\PAVO-Clinic.exe", UseShellExecute = true };
                Process.Start(processStartInfo);
                if (Application.MessageLoop)
                {
                    Application.Exit();
                }
                else
                {
                    Environment.Exit(1);
                }
            }
            catch (Exception ex)
            {
                 MessageBox.Show(ex.Message);
            }
        }

        private static string GetFileName(string url)
        {
            var fileName = string.Empty;

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            httpWebRequest.Method = "HEAD";
            httpWebRequest.AllowAutoRedirect = false;
            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            if (httpWebResponse.StatusCode.Equals(HttpStatusCode.Redirect) || httpWebResponse.StatusCode.Equals(HttpStatusCode.Moved) || httpWebResponse.StatusCode.Equals(HttpStatusCode.MovedPermanently))
            {
                if (httpWebResponse.Headers["Location"] != null)
                {
                    var location = httpWebResponse.Headers["Location"];
                    fileName = GetFileName(location);
                    return fileName;
                }
            }
            if (httpWebResponse.Headers["content-disposition"] != null)
            {
                var contentDisposition = httpWebResponse.Headers["content-disposition"];
                if (!string.IsNullOrEmpty(contentDisposition))
                {
                    const string lookForFileName = "filename=";
                    var index = contentDisposition.IndexOf(lookForFileName, StringComparison.CurrentCultureIgnoreCase);
                    if (index >= 0)
                        fileName = contentDisposition.Substring(index + lookForFileName.Length);
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Substring(1, fileName.Length - 2);
                    }
                }
            }
            if (string.IsNullOrEmpty(fileName))
            {
                var uri = new Uri(url);

                fileName = Path.GetFileName(uri.LocalPath);
            }
            return fileName;
        }
    }
}
